package com.starbaba.system.common;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.starbaba.core.exception.TaskException;
import com.starbaba.core.service.CommonService;
import com.starbaba.core.utils.SpringContextManager;


/**
 * 异步执行工厂类
 *
 * @Copyright: Copyright (c) 2006
 * @Company: Revenco Tech Ltd.
 * @anthor chenminhui<chenminhui@revenco.com>
 * @since 2014-9-12 下午02:34:46
 * @version V1.0
 */
public class AsynchronousTaskFactory {
	private static Log log = LogFactory.getLog(AsynchronousTaskFactory.class);
	
	private static AsynchronousTaskFactory ME = null;
	
	private static int POOL_SIZE = 5;
	
	/**
	 * 获取异步执行工厂类
	 * 
	 * @return AsynchronousTaskFactory
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-9-12 下午02:42:30
	 * @version V1.0
	 */
	public static AsynchronousTaskFactory getFactory() {
		if(ME == null) {
			synchronized (AsynchronousTaskFactory.class) {
				if(ME == null) {
					ME = new AsynchronousTaskFactory();
				}
			}
		}
		
		return ME;
	}
	
	
	private ScheduledExecutorService scheExecutor;
	private CommonService service;
	
	private AsynchronousTaskFactory() {
		scheExecutor = Executors.newScheduledThreadPool(POOL_SIZE);
		service = SpringContextManager.getBean("commonServiceImpl");
	}
	
	/**
	 * 异步新增VO
	 * 
	 * @param vo 对象
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-9-12 下午02:45:41
	 * @version V1.0
	 * @throws TaskException 
	 */
	public void createVO(Object vo) throws TaskException {
		if(vo != null) {
			scheExecutor.submit(new CreateVoTask(service, vo));
		} else {
			String errmsg = "VO对象不能为空";
			log.error(errmsg);
			throw new TaskException(errmsg);
		}
	}
	
	/**
	 * 新增异步任务
	 * 
	 * @param run 任务
	 * @throws TaskException
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-9-12 下午03:12:48
	 * @version V1.0
	 */
	public void addTask(Runnable run) throws TaskException {
		if(run != null) {
			scheExecutor.submit(run);
		} else {
			String errmsg = "任务对象不能为空";
			log.error(errmsg);
			throw new TaskException(errmsg);
		}
	}
	
	public void addRateTask(Runnable run,long period) throws TaskException
	{
		if(run != null) {
			scheExecutor.scheduleAtFixedRate(run,0,period,TimeUnit.MILLISECONDS);
		} else {
			String errmsg = "任务对象不能为空";
			log.error(errmsg);
			throw new TaskException(errmsg);
		}
	}
}
